package com.agile.leetcode.baiduai.token;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * 获取百度ai的token
 *
 * @Author:ChenZhangKun
 * @Date: 2021/10/14 10:08
 */
public class TokenUtil {
    public static String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=APPID&client_secret=SECRET";

    public static String getToken(String appId, String secret) {
        try {
            url = url.replaceAll("APPID", appId).replaceAll("SECRET", secret);
            URL realUrl = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) realUrl.openConnection();
            // 请求方式
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = httpURLConnection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        System.out.println(getToken(TokenConstant.App_key.getValue(), TokenConstant.Secret_key.getValue()));
    }
}
